import React, { useState, useRef, useEffect } from 'react';
import { 
  Card, 
  Input, 
  Button, 
  List, 
  Avatar, 
  Typography, 
  Space, 
  message, 
  Spin,
  Empty,
  Divider
} from 'antd';
import { 
  RobotOutlined, 
  UserOutlined, 
  SendOutlined,
  DeleteOutlined,
  ReloadOutlined
} from '@ant-design/icons';
import { aiChatService } from '../services/aiChatService';

const { Title, Text } = Typography;
const { TextArea } = Input;

const AiChat = () => {
  const [messages, setMessages] = useState([]);
  const [inputMessage, setInputMessage] = useState('');
  const [loading, setLoading] = useState(false);
  const [serviceStatus, setServiceStatus] = useState(null);
  const messagesEndRef = useRef(null);

  useEffect(() => {
    checkServiceHealth();
    // 添加欢迎消息
    setMessages([{
      id: Date.now(),
      content: '您好！我是AI助手，有什么可以帮助您的吗？',
      isUser: false,
      timestamp: new Date()
    }]);
  }, []);

  useEffect(() => {
    scrollToBottom();
  }, [messages]);

  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  };

  const checkServiceHealth = async () => {
    try {
      const response = await aiChatService.checkHealth();
      setServiceStatus(response.success ? 'online' : 'offline');
    } catch (error) {
      setServiceStatus('offline');
    }
  };

  const handleSendMessage = async () => {
    if (!inputMessage.trim()) {
      message.warning('请输入消息内容');
      return;
    }

    const userMessage = {
      id: Date.now(),
      content: inputMessage,
      isUser: true,
      timestamp: new Date()
    };

    setMessages(prev => [...prev, userMessage]);
    setInputMessage('');
    setLoading(true);

    try {
      const response = await aiChatService.sendMessage(inputMessage);
      
      if (response.success && response.data) {
        const aiMessage = {
          id: Date.now() + 1,
          content: response.data.reply,
          isUser: false,
          timestamp: new Date(),
          model: response.data.model
        };
        setMessages(prev => [...prev, aiMessage]);
      } else {
        throw new Error(response.message || 'AI回复失败');
      }
    } catch (error) {
      console.error('发送消息失败:', error);
      const errorMessage = {
        id: Date.now() + 1,
        content: `抱歉，发生了错误：${error.response?.data?.message || error.message || '未知错误'}`,
        isUser: false,
        timestamp: new Date(),
        isError: true
      };
      setMessages(prev => [...prev, errorMessage]);
      message.error('发送消息失败');
    } finally {
      setLoading(false);
    }
  };

  const handleKeyPress = (e) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSendMessage();
    }
  };

  const clearMessages = () => {
    setMessages([{
      id: Date.now(),
      content: '对话已清空，有什么可以帮助您的吗？',
      isUser: false,
      timestamp: new Date()
    }]);
  };

  const formatTime = (timestamp) => {
    return new Date(timestamp).toLocaleTimeString('zh-CN', {
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  return (
    <div className="page-content">
      <div className="page-header">
        <Space align="center" style={{ justifyContent: 'space-between', width: '100%' }}>
          <Title level={2}>AI 对话</Title>
          <Space>
            <Text type={serviceStatus === 'online' ? 'success' : 'danger'}>
              服务状态: {serviceStatus === 'online' ? '在线' : '离线'}
            </Text>
            <Button icon={<ReloadOutlined />} onClick={checkServiceHealth} size="small">
              刷新状态
            </Button>
            <Button icon={<DeleteOutlined />} onClick={clearMessages} size="small">
              清空对话
            </Button>
          </Space>
        </Space>
      </div>

      <Card className="card-container" style={{ height: 'calc(100vh - 200px)', display: 'flex', flexDirection: 'column' }}>
        {/* 消息列表区域 */}
        <div style={{ 
          flex: 1, 
          overflowY: 'auto', 
          marginBottom: 16,
          padding: '0 8px',
          maxHeight: 'calc(100vh - 350px)'
        }}>
          {messages.length === 0 ? (
            <Empty description="暂无对话消息" />
          ) : (
            <List
              dataSource={messages}
              renderItem={(item) => (
                <List.Item
                  style={{
                    border: 'none',
                    padding: '12px 0',
                    justifyContent: item.isUser ? 'flex-end' : 'flex-start'
                  }}
                >
                  <div style={{
                    display: 'flex',
                    alignItems: 'flex-start',
                    flexDirection: item.isUser ? 'row-reverse' : 'row',
                    maxWidth: '80%'
                  }}>
                    <Avatar 
                      icon={item.isUser ? <UserOutlined /> : <RobotOutlined />}
                      style={{ 
                        marginLeft: item.isUser ? 8 : 0,
                        marginRight: item.isUser ? 0 : 8,
                        backgroundColor: item.isUser ? '#1890ff' : '#52c41a'
                      }}
                    />
                    <div style={{
                      background: item.isUser ? '#e6f7ff' : (item.isError ? '#fff2f0' : '#f6ffed'),
                      padding: '8px 12px',
                      borderRadius: '8px',
                      border: `1px solid ${item.isUser ? '#91d5ff' : (item.isError ? '#ffccc7' : '#b7eb8f')}`,
                      maxWidth: '100%'
                    }}>
                      <div style={{ 
                        whiteSpace: 'pre-wrap', 
                        wordBreak: 'break-word',
                        color: item.isError ? '#cf1322' : 'inherit'
                      }}>
                        {item.content}
                      </div>
                      <div style={{ 
                        fontSize: '12px', 
                        color: '#999', 
                        marginTop: '4px',
                        textAlign: item.isUser ? 'right' : 'left'
                      }}>
                        {formatTime(item.timestamp)}
                        {item.model && ` • ${item.model}`}
                      </div>
                    </div>
                  </div>
                </List.Item>
              )}
            />
          )}
          <div ref={messagesEndRef} />
        </div>

        <Divider style={{ margin: '16px 0' }} />

        {/* 输入区域 */}
        <div>
          <Space.Compact style={{ width: '100%' }}>
            <TextArea
              value={inputMessage}
              onChange={(e) => setInputMessage(e.target.value)}
              onKeyPress={handleKeyPress}
              placeholder="输入您的消息... (按 Enter 发送，Shift + Enter 换行)"
              autoSize={{ minRows: 1, maxRows: 4 }}
              disabled={loading}
              style={{ flex: 1 }}
            />
            <Button
              type="primary"
              icon={loading ? <Spin size="small" /> : <SendOutlined />}
              onClick={handleSendMessage}
              loading={loading}
              disabled={!inputMessage.trim() || serviceStatus !== 'online'}
              style={{ height: 'auto' }}
            >
              发送
            </Button>
          </Space.Compact>
          <div style={{ marginTop: '8px', fontSize: '12px', color: '#999' }}>
            提示：按 Enter 发送消息，Shift + Enter 换行
          </div>
        </div>
      </Card>
    </div>
  );
};

export default AiChat;